package ibm.abacus.classpath;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class LoadClassFromFile {

	static class ClassFileLoader extends ClassLoader {
		public void readClassFromFile(String file) throws IOException {
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			int length = (int) raf.length();
			FileChannel channel = raf.getChannel();
			MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, length);
			byte[] data = new byte[length];
			for (int i = 0; i < length; i++) {
				data[i] = mbb.get();
			}
			raf.close();
			Class<?> defineClass = defineClass(data, 0, length);
			System.out.println(defineClass.getCanonicalName());
		}

		private void readClassFile(File file) {
			if (file != null && file.exists()) {
				if (file.isDirectory()) {
					
				}
			}
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		ClassFileLoader loader = new ClassFileLoader();
		loader.readClassFromFile("D:\\workspace\\eclipse\\ibm.abacus.quote\\bin\\ibm\\abacus\\quote\\Trd.class");
		
		try {
			
			Class<?> loadClass = loader.loadClass("ibm.abacus.quote.Trd");
			System.out.println(loadClass.getName());
			
//			ClassLoader.getSystemClassLoader()
//			.loadClass("ibm.abacus.quote.Trd");
			
			Thread.currentThread().setContextClassLoader(loader);
			
			
			while(true){
				System.out.println(loadClass.getClassLoader().toString());
				
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
